const router = require("express").Router()
const fs = require("fs")
const Dramas = require("../models/Dramas")
const multer = require("multer")
const { v4: uuidv4 } = require("uuid")
const { uploadCoverImage } = require("../controllers/uploadControllers")

const uploadImage = (dir) => {



    const DIR = './public/' + dir
    if (!fs.existsSync(DIR)) {
        fs.mkdirSync(DIR)
    }

    const Storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, DIR)
        },
        filename: (req, file, cb) => {
            const fileName = file.originalname.toLowerCase().split(" ").join("-")
            cb(null, uuidv4() + "-" + fileName)
        }
    })

    var upload = multer({
        storage: Storage,
        fileFilter: async (req, file, cb) => {
            try{
                await Dramas.findById(req.body._id)
                if (file.mimetype == 'image/png' || file.mimetype == 'image/jpg' || file.mimetype == 'image/jpeg') {
                    cb(null, true)
                }
                else {
                    cb(null, false)
                    cb("只允许上传.png.jpg.jpeg格式文件")
                }
            }
            catch{
                cb(null, false)
                cb("未找到该剧本")
            }

        }
    })
    return upload.single("avatar");
}


router.post('/drama_Cover', uploadImage("drama_Cover"), uploadCoverImage)
router.post('/drama_Image_Role', uploadImage("drama_Image_Role"), uploadCoverImage)


module.exports = router